<template>
  <div class="app-container">
    <!-- 欢迎信息与果园图片轮播 -->
    <el-row :gutter="20" style="margin-bottom: 40px;">
      <el-col :span="24">
        <el-carousel :interval="5000" arrow="always" height="300px" class="welcome-banner">
          <el-carousel-item v-for="(image, index) in orchardImages" :key="index">
            <img :src="image.src" alt="果园风景" />
            <div class="overlay">
              <h1>欢迎来到果园农事管理系统</h1>
              <p>在这里，您可以轻松管理果园信息、物资信息、安排农事任务和处理物资维修。</p>
            </div>
          </el-carousel-item>
        </el-carousel>
      </el-col>
    </el-row>

    <!-- 当日及未来天气 -->
    <el-row :gutter="20" style="margin-bottom: 10px;">
      <el-col :span="24">
        <el-card shadow="hover" class="weather-strip">
          <div class="weather-today">
            <div class="weather-info">
              <h3>今日天气</h3>
              <h2>{{ weather ? weather.today.temperature + '°C' : '' }}</h2>
            </div>
            <div class="city-name">
              <p>广州</p>
            </div>
            <div class="weather-icon">
              <img v-if="weather && weather.today.weatherImg" :src="weather.today.weatherImg" alt="Weather Icon" />
            </div>
          </div>
          <div class="forecast-strip">
            <div v-for="(day, index) in weather ? weather.forecast : []" :key="index" class="forecast-item">
              <div class="forecast-date">{{ day.date }}</div>
              <img :src="day.weatherImg" alt="Weather Icon" />
              <div class="forecast-details">
                <div class="forecast-temp">{{ day.tempMin }}°/{{ day.tempMax }}°</div>
                <div class="forecast-other">{{ day.windDirection }}, {{ day.windSpeed }}</div>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 果树占比饼图 和 农事活动列表 -->
    <el-row :gutter="20">
      <el-col :span="12">
        <el-card shadow="hover" class="pie-chart-card">
          <div slot="header" class="clearfix card-header">
            <span>果树种类占比</span>
          </div>
          <div id="fruit-pie-chart" style="width: 100%; height: 300px;"></div>
        </el-card>
      </el-col>

      <el-col :span="12">
        <el-card shadow="hover" class="agricultural-tasks-card">
          <div slot="header" class="clearfix card-header">
            <span>未来一周农事活动</span>
          </div>
          <ul class="task-list">
            <li v-for="(task, index) in upcomingTasks" :key="task.id" :class="{ 'important-task': task.isImportant }">
              <span v-if="task.isImportant" class="task-flag">!</span>
              <strong>{{ task.name }}</strong><br>
              <span>描述: {{ task.description }}</span><br>
              <span>创建时间: {{ formatDate(task.createdAt) }}</span><br>
              <span>截止时间: {{ formatDate(task.endDate) }}</span><br>
              <span>果园信息: {{ task.orchardInfo }}</span><br>
              <span>所需材料/工具: {{ task.materialsTools }}</span><br>
              <span>负责人: {{ task.assignees.join(', ') }}</span><br>
              <span>状态: {{ task.status }}</span>
            </li>
          </ul>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import * as echarts from 'echarts';
import { mapState, mapActions } from 'vuex';

export default {
  data() {
    return {
      weather: null, // 初始为空，等待API响应填充
      myChart: null, // 用来保存 ECharts 实例
      orchardImages: [
        { src: 'https://res.klook.com/images/fl_lossy.progressive,q_65/c_fill,w_1200,h_630/w_80,x_15,y_15,g_south_west,l_Klook_water_br_trans_yhcmh3/activities/gxubepyyfjbu8npyzx8l/%E5%9C%A8%20CherryHill%20%E6%9E%9C%E5%9C%92%E6%8E%A1%E6%91%98%E6%AB%BB%E6%A1%83.jpg' },
        { src: 'https://pic.616pic.com/bg_w1180/00/06/39/LGcxvCqrsO.jpg' },
        { src: 'https://cc.tvbs.com.tw/img/program/upload/2020/06/20/20200620175828-32a67560.jpg' }
      ]
    };
  },
  computed: {
    ...mapState('orchardinfo', ['orchards', 'loading', 'error']),
    ...mapState('task', ['tasks']), // 映射任务列表
    upcomingTasks() {
      const today = new Date();
      const oneWeekLater = new Date(today);
      oneWeekLater.setDate(today.getDate() + 7);

      return this.tasks.filter(task => {
        const endDate = new Date(task.endDate);
        return endDate >= today && endDate <= oneWeekLater;
      });
    }
  },
  methods: {
    ...mapActions('orchardinfo', ['fetchOrchards']),
    ...mapActions('task', ['fetchTasks']), // 映射获取任务的 action
    async fetchWeatherData() {
      try {
        const response = await fetch('https://hmajax.itheima.net/api/weather?city=440100');
        const data = await response.json();

        if (data.code === 10000) {
          this.weather = {
            today: {
              temperature: data.data.temperature,
              windDirection: data.data.windDirection,
              windSpeed: data.data.windPower,
              weatherImg: data.data.weatherImg
            },
            forecast: data.data.dayForecast.map(day => ({
              date: day.date,
              tempMin: day.temNight,
              tempMax: day.temDay,
              windDirection: day.windDirection,
              windSpeed: day.windPower,
              weatherImg: day.weatherImg
            }))
          };
        } else {
          console.error('Error fetching weather data:', data.message);
        }
      } catch (error) {
        console.error('Error fetching weather data:', error);
      }
    },
    initFruitPieChart() {
      this.$nextTick(() => {
        const chartDom = document.getElementById('fruit-pie-chart');
        if (chartDom) {
          this.myChart = echarts.init(chartDom);

          let fruitData = this.getFruitData();

          const option = {
            title: {
              text: '果树种类占比',
              left: 'center',
              textStyle: { fontSize: 16, fontWeight: 'bold' }
            },
            tooltip: {
              trigger: 'item'
            },
            legend: {
              orient: 'vertical',
              left: 'left',
              top: 'middle',
              textStyle: { color: '#333' }
            },
            series: [
              {
                name: 'Access From',
                type: 'pie',
                radius: '50%',
                data: fruitData,
                emphasis: {
                  itemStyle: {
                    shadowBlur: 10,
                    shadowOffsetX: 0,
                    shadowColor: 'rgba(0, 0, 0, 0.5)'
                  }
                }
              }
            ]
          };

          this.myChart.setOption(option);
        } else {
          console.error('ECharts container not found!');
        }
      });
    },
    getFruitData() {
      if (!this.orchards) return [];

      const countMap = this.orchards.reduce((acc, orchard) => {
        acc[orchard.cropType] = (acc[orchard.cropType] || 0) + (orchard.plantCount || 0);
        return acc;
      }, {});

      return Object.entries(countMap).map(([name, value]) => ({ name, value }));
    },
    formatDate(dateString) {
      const options = { year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', second: '2-digit' };
      return new Date(dateString).toLocaleDateString(undefined, options);
    }
  },
  mounted() {
    this.fetchWeatherData();
    this.fetchOrchards().then(() => {
      this.initFruitPieChart(); // 确保在果园信息加载完成后初始化图表
    }).catch(error => {
      console.error('Error fetching orchard info:', error);
    });

    this.fetchTasks(); // 加载任务列表
  },
  watch: {
    orchards(newVal) {
      if (this.myChart && newVal) {
        this.myChart.setOption({
          series: [{
            data: this.getFruitData()
          }]
        });
      }
    }
  }
};
</script>



















<style scoped>
.app-container {
  padding: 20px;
  background-color: #ffffff;
  min-height: 100vh;
}

.el-card__body {
  padding: 5px !important;
}

.welcome-banner {
  position: relative;
  border-radius: 15px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.welcome-banner img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 15px;
}

.overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: linear-gradient(to bottom, rgba(0, 0, 0, 0.7), transparent);
  color: white;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  text-align: center;
  padding: 20px;
}

.overlay h1 {
  font-size: 2em;
  margin: 0;
  font-weight: bold;
}

.weather-strip {
  display: flex;
  flex-direction: column;
  background-image: url('https://cdn.pixabay.com/photo/2016/11/05/12/38/fuzzy-1800136_640.jpg');
  background-size: cover;
  background-position: center;
  border-radius: 15px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  padding: 0px;
  margin-bottom: 20px;
  color: #fff;
  position: relative;
  height: 230px;
}

.weather-strip::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  z-index: -1;
}

.weather-today {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 15px;
  flex: 0 0 auto;
  height: 60px;
}

.weather-info {
  color: #fff;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.weather-info h3 {
  font-size: 1em;
  margin-bottom: 0;
}

.weather-info h2 {
  font-size: 1.2em;
  margin: 0;
}

.city-name {
  flex-grow: 1;
  text-align: right;
  margin-left: auto;
  color: #fff;
  font-size: 1em;
  font-weight: bold;
}

.weather-icon {
  font-size: 36px;
  margin-left: 10px;
}

.forecast-strip {
  display: flex;
  flex-wrap: nowrap;
  gap: 5px;
  flex-grow: 1;
  overflow-x: auto;
  padding-bottom: 5px;
}

.forecast-item {
  background-color: rgba(255, 255, 255, 0.8);
  border-radius: 10px;
  padding: 10px;
  flex-shrink: 0;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  text-align: center;
  transition: transform 0.2s ease-in-out;
  font-size: 0.8em;
  min-width: 100px;
}

.forecast-date {
  font-size: 0.9em;
  margin-bottom: 5px;
  color: #000;
}

.forecast-details {
  margin-top: 5px;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.forecast-temp {
  font-size: 1em;
  font-weight: bold;
  color: #000;
  margin-bottom: 2px;
}

.forecast-other {
  font-size: 0.8em;
  color: #777;
}

.card-header {
  font-size: 1.2em;
  font-weight: bold;
  color: #333;
}

.agricultural-tasks-card .task-list {
  list-style-type: none;
  padding-left: 0;
}

.agricultural-tasks-card .task-list li {
  padding: 15px;
  border-bottom: 1px solid #f0f0f0;
  transition: background-color 0.3s;
  background: #f9f9f9;
  /* 背景颜色 */
  border-radius: 8px;
  /* 圆角 */
  margin-bottom: 10px;
  /* 任务之间的间距 */

  &:last-child {
    border-bottom: none;
  }

  &.important-task {
    background-color: #ffefef;
    border-left: 5px solid red;
    /* 突出重要任务 */
  }

  strong {
    display: block;
    margin-bottom: 5px;
    font-size: 1.1em;
    /* 加大标题字体 */
    color: #333;
    /* 深色文字 */
  }

  span {
    font-size: 0.9em;
    color: #777;
    display: block;
    margin-bottom: 4px;
  }

  .task-flag {
    color: red;
    font-weight: bold;
    margin-right: 5px;
  }

  .task-description {
    font-size: 0.9em;
    color: #555;
    margin-bottom: 6px;
  }

  .task-metadata {
    display: flex;
    flex-wrap: wrap;
    gap: 10px;
  }

  .metadata-item {
    display: flex;
    align-items: center;
    gap: 5px;
  }

  .metadata-icon {
    width: 16px;
    height: 16px;
  }
}</style>